<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>新增借货返库订单</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        //此角色的最大折扣权限。        
        //是否临时保存
        var temporary = new Ext.form.Hidden({
          name: 'temporary',
          value: 0
        });

        var loanId = new Ext.form.Hidden({
          name: 'loan_id',
          value: <%=params[:id]%>
        });

        //所有仓库
        var warehouseTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '{number}|{name}', '</div></tpl>');
        var warehouseStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/warehouse/getAllWarehouse?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }])
        });
        
        var toWarehouse = new Ext.form.ComboBox({
          store: warehouseStore,
          fieldLabel: '到仓库',
          allowBlank: false,
          blankText: "仓库必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'warehouse_id',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '90%',
          //pageSize: 10,
          //hideTrigger: false,
          tpl: warehouseTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          triggerAction: 'all',
          editable:false,
          selectOnFocus:true
        });
        
        //备注
        var desc = new Ext.form.TextField({
          fieldLabel: '备注',
          name: 'description',
          anchor: '100%'
        });

        //要求发货时间
        var actionDate = new Ext.form.DateField({
          fieldLabel: '返库日期',
          name: 'action_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          allowBlank: false,
          blankText: "返库日期必须选择",
          emptyText: '返库日期...'
          //anchor: '50%'
        });

        //--------------------------------------------------------------------------        
        //借货返库订单列表Grid Store
        var loanDetailDS = new Ext.data.Store({
          baseParams:{loan_id:loanId.getValue()},
          proxy: new Ext.data.HttpProxy({
            url: "/loan_returned/getProductsOfLoanForReturned"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }, {
              name: 'description'
            }, {
              name: 'quantity'
            },{
              name: 'balance_quantity'
            },{
              name: 'product_id'
            },{
              name: 'product_name'
            },{
              name: 'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }])
        });
        //生成产品Grid的CM
        var loanDetailSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        var loanDetailCM = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),loanDetailSM,{
            header: '产品名称',
            dataIndex: 'product_name',
            width: 270
          },{
            header: '产品ID',
            dataIndex: 'product_id',
            width: 50,
            hidden: false
          },{
            header: '产品编号',
            dataIndex: 'number',
            width: 70
          },{
            header: '规格',
            dataIndex: 'spec',
            width: 50
          },{
            header: '单位',
            dataIndex: 'unit',
            width: 40
          },{
            header: '数量',
            align: 'right',
            dataIndex: 'quantity',
            editor: new Ext.form.NumberField({
              allowBlank: false,
              allowDecimals: false,
              allowNegative: false
            }),
            width: 50
          },{
            header: '套装或单品',
            dataIndex: 'is_suit',
            width: 70
          },{
            header: '备注',
            dataIndex: 'description',
            width: 250,
            editor:new Ext.form.TextField({
              name: 'description',
              anchor: '100%'
            })
          }
        ]);
        loanDetailDS.load();
        
        //生成要订单的产品的Grid
        var loanDetailGrid = new Ext.grid.EditorGridPanel({
          store: loanDetailDS,
          cm: loanDetailCM,
          sm: loanDetailSM,
          width: 950,
          height: 340,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,
          clicksToEdit: 1,//这里应该是单击就可以修改的意思。因为默认是要双击的。
          tbar: [{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var record = loanDetailSM.getSelected();
                if (!record) {
                  return false;
                }
                loanDetailDS.remove(record);
              }
            }]
        });

        loanDetailGrid.on('afteredit', afterEdit, this );

        function afterEdit(obj) {
          
          if(obj.field=="quantity"){
            if (obj.record.get('quantity') > obj.record.get('balance_quantity')){
              obj.record.set('quantity',obj.record.get('balance_quantity'));
            }
          }
        }
        
        //提交按钮
        var submitButton = new Ext.Button({
          text: '提交',
          tooltip: '保存并提交借货返库订单。',
          iconCls: 'icon-save',
          handler: function(){
            //.setDisabled(true);
            //如果输入了首付金额，就要填写付款方式
            
            if (loanReturnedFormPanel.form.isValid()){
              
              var productsJsonStr = gridStoreToJson(loanDetailDS,rejectKeyArray);
              if (loanDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              //没有添加产品，则提示
              if (loanDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              
              this.disable();
              var allJsonStr = loanReturnedFormPanel.getForm().getValues();
              allJsonStr = Ext.util.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              
              Ext.Ajax.request({
                url : '/loan_returned/create',
                success : function (result, request) {
                  //Ext.MessageBox.alert("提示","提交成功");
                  newLoanReturnedWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  newLoanReturnedWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.util.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });

        //关闭按钮
        var closeButton = new Ext.Button({
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            newLoanReturnedWin.destroy();
          }
        });
        
        //采购申请的FormPanel
        var loanReturnedFormPanel = new Ext.form.FormPanel({
          //baseCls: 'x-plain',
          //renderTo: 'new_loan_returned',
          labelWidth: 55,
          width: '950',
          labelAlign: 'right',          
          frame : true,
          url: '/loan_returned/create',
          method: 'GET',
          //defaultType: 'textfield',
          items: [{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: .3,
                  layout: 'form',
                  border: false,
                  items: [toWarehouse]
                }, {
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [actionDate]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [desc]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [loanDetailGrid]
                }]
            },temporary,loanId],
          buttons: [submitButton,closeButton]
        });
        loanReturnedFormPanel.render('new_loan_returned');

      })
    </script>
  </head>
  <body>
    <div id="new_loan_returned"></div>
  </body>
</html>